﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Remoting.Lifetime;
using System.Security.Permissions;

namespace _0121_RemotingActivatedServer
{
    public class Program
    {
        static void Main(string[] args)
        {
            TcpChannel channel = new TcpChannel(9999);
            ChannelServices.RegisterChannel(channel);
            ActivatedServiceTypeEntry entry = new ActivatedServiceTypeEntry(typeof(MyServer));
            RemotingConfiguration.RegisterActivatedServiceType(entry);

            Console.WriteLine("Server configured");
            Console.ReadLine();
        }
    }


    public class MyServer : MarshalByRefObject
    {
        public MyServer()
        {
            Console.WriteLine("Server created");
        }

        public RemotingInterface.ComplexObject doSomething(String stringParam, int intParam, double doubleParam, string[] arrayParam)
        {
            Console.WriteLine("Server called");
            RemotingInterface.ComplexObject obj = new RemotingInterface.ComplexObject();
            obj.stringParam = stringParam;
            obj.intParam = intParam;
            obj.doubleParam = doubleParam;
            return obj;
        }
//*
        [SecurityPermissionAttribute(SecurityAction.LinkDemand,Flags=SecurityPermissionFlag.Infrastructure)]
        public override object InitializeLifetimeService()
        {
            Console.WriteLine("InitializeLifetimeService called");
            ILease lease = (ILease)base.InitializeLifetimeService();
            if (lease.CurrentState == LeaseState.Initial)
            {
                lease.InitialLeaseTime = TimeSpan.FromSeconds(500);
                lease.RenewOnCallTime = TimeSpan.FromSeconds(1);
                lease.SponsorshipTimeout = TimeSpan.FromSeconds(5);
                Console.WriteLine("InitializeLifetimeService set");
            }

            return lease;
        }
        //*/

    }
}
